package com.ly.ocw.web.weixin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.mapper.JaxbMapper;

import com.ly.ocw.entity.weixin.WeixinPublic;
import com.ly.ocw.service.weixin.WeixinConf;
import com.ly.ocw.service.weixin.WeixinMessageProcessService;
import com.ly.ocw.service.weixin.WeixinPublicService;
import com.ly.ocw.vo.wx.Event;
import com.ly.ocw.vo.wx.MsgType;
import com.ly.ocw.vo.wx.WeixinMessage;

/**
 * 微信开发者模式接入认证 Controller.
 * 
 * @author peter
 */
@Controller
@RequestMapping(value = "/wxserver")
public class WeixinPublicServerController {

	private static Logger logger = LoggerFactory.getLogger(WeixinPublicServerController.class);

	@Autowired
	private WeixinConf weixinConf;

	@Autowired
	private WeixinPublicService weixinPublicService;

	@Autowired
	private WeixinMessageProcessService weixinMessageProcessService;

	/**
	 * 接入认证
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		logger.info("{signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",echostr:" + echostr + "}");

		WeixinPublic weixinPublic = weixinPublicService.getById(weixinConf.getPublicId());
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce, weixinPublic.getToken())) {
			return echostr;
		}
		return "";
	}

	/**
	 * 获取微信推送过来的消息
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public String receiveWeixinMessage(@RequestBody String xml, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		logger.info("{signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",echostr:" + echostr + "}");

		logger.info("<<-------------------receiveWeixinMessage Request ---------------->>\n" + xml);

		WeixinMessage msg = JaxbMapper.fromXml(xml, WeixinMessage.class);

		String result = processWeixinMessage(msg);

		logger.info("<<-------------------receiveWeixinMessage Response ---------------->>\n" + result);
		return result;
	}

	private String processWeixinMessage(WeixinMessage msg) {

		// 文本消息
		if (MsgType.text.name().equals(msg.getMsgType())) {
			return weixinMessageProcessService.processTextMsg(msg);
		}
		// 事件消息
		else if (MsgType.event.name().equals(msg.getMsgType())) {
			// 处理事件消息
			if (Event.subscribe.name().equals(msg.getEvent())) {

				if (StringUtils.isNotBlank(msg.getEventKey()) && msg.getEventKey().startsWith("qrscene_")) {
					// 扫描带参数二维码事件:用户未关注时，进行关注后的事件推送
					return weixinMessageProcessService.processScanForSubscribe(msg);
				} else {
					// 普通订阅
					return weixinMessageProcessService.processSubscribeMsg(msg);
				}

			} else if (Event.unsubscribe.name().equals(msg.getEvent())) {
				// 取消订阅
				weixinMessageProcessService.processUnsubscribe(msg);

			} else if (Event.SCAN.name().equals(msg.getEvent())) {
				// 扫描带参数二维码事件:用户已关注时的事件推送
				return weixinMessageProcessService.processScan(msg);

			} else if (Event.CLICK.name().equals(msg.getEvent())) {
				// 点击菜单事件
				return weixinMessageProcessService.processClick(msg);

			} else if (Event.user_get_card.name().equals(msg.getEvent())) {
				// 用户领取卡券事件
				return weixinMessageProcessService.processUserGetCard(msg);

			} else if (Event.user_del_card.name().equals(msg.getEvent())) {
				// 用户删除卡券事件
				return weixinMessageProcessService.processUserDelCard(msg);

			} else if (Event.user_view_card.name().equals(msg.getEvent())) {
				// 用户查看卡券事件
				return weixinMessageProcessService.processUserViewCard(msg);

			} else if (Event.card_pass_check.name().equals(msg.getEvent())) {
				// 卡券审核通过事件
				return weixinMessageProcessService.processCardPassCheck(msg);

			} else if (Event.card_not_pass_check.name().equals(msg.getEvent())) {
				// 卡券审核不通过事件
				return weixinMessageProcessService.processCardNotPassCheck(msg);

			}

		} else {
			logger.info("未识别消息类型");
		}

		return "";
	}

	/**
	 * 获取孩子王推送过来的微信消息
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "receiveWeixinMessageFromHzw", method = RequestMethod.POST)
	@ResponseBody
	public String receiveWeixinMessageFromHzw(@RequestBody String xml, HttpServletRequest request, HttpServletResponse response, Model model) {
		String result = "{\"errcode\":0,\"errmsg\":\"ok\"}";
		try {
			// 微信加密签名
			String signature = request.getParameter("signature");
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			// 随机数
			String nonce = request.getParameter("nonce");
			// 随机字符串
			String echostr = request.getParameter("echostr");
			logger.trace("{signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",echostr:" + echostr + "}");
			logger.trace("<<-------------------receiveWeixinMessageFromHzw ---------------->>\n" + xml);
			
			WeixinMessage msg = JaxbMapper.fromXml(xml, WeixinMessage.class);
			processWeixinMessageFromHzw(msg);
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = "{\"errcode\":1,\"errmsg\":\"系统繁忙\"}";
		}
		logger.trace("<<-------------------receiveWeixinMessageFromHzw Response ---------------->>\n" + result);
		return result;
	}

	private void processWeixinMessageFromHzw(WeixinMessage msg) {

		// 文本消息
		if (MsgType.text.name().equals(msg.getMsgType())) {
			
			logger.trace("文本消息");
		}
		// 事件消息
		else if (MsgType.event.name().equals(msg.getMsgType())) {
			if (Event.user_get_card.name().equals(msg.getEvent())) {
				// 用户领取卡券事件
				weixinMessageProcessService.processUserGetCard(msg);

			} else if (Event.user_del_card.name().equals(msg.getEvent())) {
				// 用户删除卡券事件
				weixinMessageProcessService.processUserDelCard(msg);

			} else if (Event.user_view_card.name().equals(msg.getEvent())) {
				// 用户查看卡券事件
				weixinMessageProcessService.processUserViewCard(msg);

			} else if (Event.card_pass_check.name().equals(msg.getEvent())) {
				// 卡券审核通过事件
				weixinMessageProcessService.processCardPassCheck(msg);

			} else if (Event.card_not_pass_check.name().equals(msg.getEvent())) {
				// 卡券审核不通过事件
				weixinMessageProcessService.processCardNotPassCheck(msg);
			} else {
				logger.trace("其他事件（非卡券相关）");
			}

		} else {
			logger.trace("未识别消息类型");
		}

	}

}
